package com.reagent.system.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.reagent.response.Result;
import com.reagent.response.ResultCode;
import com.reagent.utils.JWTUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@Api(tags = "公共接口")
@ApiResponses({
        @ApiResponse(code = 200, message = "成功"),
        @ApiResponse(code = 201, message = "成功创建资源"),
        @ApiResponse(code = 400, message = "失败"),
        @ApiResponse(code = 401, message = "服务器认证失败"),
        @ApiResponse(code = 403, message = "资源不存在"),
        @ApiResponse(code = 404, message = "页面不存在"),
        @ApiResponse(code = 500, message = "服务器异常")
})
@RestController
@Slf4j
public class CommonController {

    @ApiOperation(value = "获取Token", notes = "获取Token进行校验并获取值")
    @GetMapping("/getToken")
    public Object getToken() {
        String token = JWTUtils.getCurrentToken();
        if (ObjectUtils.isEmpty(token)) {
            log.warn("你的身份信息过期或你未登录");
            return Result.error().message("你的身份信息过期或你未登录").code(ResultCode.TOKEN_EXPIRED.getStatus());
        }
        DecodedJWT decodedJWT = JWTUtils.verifyToken(token);
        log.info("Token验证成功...");
        HashMap<String, String> map = new HashMap<>();
        map.put("id", decodedJWT.getClaim("id").asString());
        map.put("username", decodedJWT.getClaim("username").asString());
        map.put("rid", decodedJWT.getClaim("rid").asString());
        return Result.success().data(map);
    }
}
